<template>
  <el-dialog
    v-model="visibleLocal"
    :title="mode === 'create' ? '新增组织' : '编辑组织'"
    width="600px"
    destroy-on-close
    @closed="handleClosed"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="组织名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入组织名称" />
      </el-form-item>
      <el-form-item label="组织类型" prop="org_type">
        <el-select v-model="form.org_type" placeholder="请选择组织类型">
          <el-option
            v-for="item in ORG_TYPE_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人ID" prop="owner_user_id">
        <el-input v-model="form.owner_user_id" placeholder="负责人用户ID" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  ORG_TYPE_OPTIONS,
  createOrganization,
  updateOrganization,
  type OrganizationListItem
} from "@/api/system/org/organization";

const props = defineProps<{
  visible: boolean;
  mode: "create" | "edit";
  organization: OrganizationListItem | null;
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}>();

const formRef = ref();
const submitting = ref(false);
const visibleLocal = ref(props.visible);

const form = reactive({
  name: "",
  org_type: "seller",
  owner_user_id: "",
  remark: ""
});

const rules = {
  name: [{ required: true, message: "请输入组织名称", trigger: "blur" }]
};

const assignForm = (organization: OrganizationListItem | null) => {
  if (!organization) {
    form.name = "";
    form.org_type = "seller";
    form.owner_user_id = "";
    form.remark = "";
    return;
  }
  form.name = organization.name ?? "";
  form.org_type = organization.org_type ?? "seller";
  form.owner_user_id = organization.owner_user_id
    ? String(organization.owner_user_id)
    : "";
  form.remark = organization.extra?.remark ?? organization.remark ?? "";
};

watch(
  () => props.visible,
  value => {
    visibleLocal.value = value;
  }
);

watch(
  () => props.organization,
  value => {
    if (props.mode === "edit") {
      assignForm(value ?? null);
    }
  },
  { immediate: true }
);

const handleClose = () => {
  visibleLocal.value = false;
  emit("update:visible", false);
};

const handleClosed = () => {
  assignForm(props.mode === "edit" ? props.organization ?? null : null);
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  submitting.value = true;
  try {
    const payload = {
      name: form.name,
      org_type: form.org_type,
      owner_user_id: form.owner_user_id
        ? Number(form.owner_user_id)
        : undefined,
      remark: form.remark
    };

    if (props.mode === "edit" && props.organization) {
      await updateOrganization(props.organization.id, payload);
      ElMessage.success("组织已更新");
    } else {
      await createOrganization(payload);
      ElMessage.success("组织已创建");
    }

    emit("success");
    handleClose();
  } catch (error: any) {
    ElMessage.error(error?.message ?? "保存组织失败");
  } finally {
    submitting.value = false;
  }
};
</script>
